'use strict';

let { Users } = require('../models');
const auth = require('../utils/auth');
const survey = require('./survey');

let login_fn = async (ctx, next) => {
    // ctx.session.userId = null;
    ctx.render('login.html');
}

let login_judge_fn = async (ctx, next) => {
    let uid = ctx.request.body.username.trim();
    let pwd = ctx.request.body.password.trim();

    let surveyId = ctx.session.surveyId;
    // console.log("ctx:"+ctx.session.surveyId);

    let res = '';

    let user = await Users.findOne({ where: { username: uid }, raw: true });

    //这里要给判断是否为冻结用户或者是否被删除
    if (user) {
        if(user.isActive === "1"){
            if(user.isDelete === "0"){
                if (user.password === pwd) { 
                    if (user.role === "1") {
                        if(!surveyId){
                            ctx.session.userId = user.id;
                            ctx.session.userName = user.username;
                            ctx.session.role = user.role;
                            res = { code: 200};
                        }else{
                            ctx.session.userId = user.id;
                            ctx.session.userName = user.username;
                            ctx.session.role = user.role;
                            // ctx.redirect(`/surveyAll/${surveyId}`);
                            res = {code:202,id:surveyId}
                        }
                        // ctx.redirect('/surveyAll');
                        
                    } else {
                        ctx.session.userId = user.id;
                        ctx.session.userName = user.username;
                        ctx.session.role = user.role;
                        // ctx.redirect('/rootindex');
                        res = { code: 200};
                    }
        
                } else {
                    res = { code: 400, msg: '密码不正确，请重新输入' };
                }
            }else{
                res = { code: 400, msg: '用户已被删除，请联系管理员' };
            }
        }else{
            res = { code: 400, msg: '用户已被冻结，请联系管理员' };
        }  
    } else {
        res = { code: 400, msg: '用户不存在，请注册' };
    }

    ctx.body = JSON.stringify(res);

}



let logout_fn = async (ctx, next) => {
    ctx.session = null;
    ctx.body = { code: 200 };
}


module.exports = {
    '/login': ['get', auth, login_fn],
    '/logout': ['post', auth, logout_fn],
    '/login/judge': ['post', login_judge_fn],
}